package com.example.administrator.ttphonehelper.process;

import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.administrator.ttphonehelper.R;

import java.util.ArrayList;
import java.util.List;

public class ProcessActivity extends AppCompatActivity {
    private TabLayout mTabLayout;
    private ViewPager mViewPager;
    private MyPagerAdapter mAdapter;
    private static final int[] IMG_IDS = {R.mipmap.phone_speed,R.mipmap.phone_sys};
    private static final String[] ICON_TEXTS={"进程管理","硬件信息"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_process);
        mTabLayout = (TabLayout) findViewById(R.id.tab_layout);
        mViewPager = (ViewPager) findViewById(R.id.viewpager);
        mViewPager.setOffscreenPageLimit(2);
        setViewPager(mViewPager);

        mTabLayout.addTab(mTabLayout.newTab());
        mTabLayout.addTab(mTabLayout.newTab());
        //TabLayout与ViewPager关联
        mTabLayout.setupWithViewPager(mViewPager);

        //为TabLayout的Item赋值
        for (int i = 0; i <mTabLayout.getTabCount() ; i++) {
            TabLayout.Tab tab = mTabLayout.getTabAt(i);
            if(tab!=null){
                tab.setCustomView(mAdapter.getTabView(i));
            }
        }
    }

    private void setViewPager(ViewPager viewPager) {
        mAdapter  = new MyPagerAdapter(getSupportFragmentManager());
        mAdapter.addFragment(new ProcessFragment());
        mAdapter.addFragment(new DeviceFragment());
        viewPager.setAdapter(mAdapter);

    }

    //ViewPager适配器
    public class MyPagerAdapter extends FragmentPagerAdapter {
        private final List<Fragment> mFragments = new ArrayList<>();

        public MyPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        public void addFragment(Fragment fragment) {
            mFragments.add(fragment);

        }

        @Override
        public Fragment getItem(int position) {
            return mFragments.get(position);
        }

        @Override
        public int getCount() {
            return mFragments.size();
        }
        //设置每一个TabLayout条目的图像跟文字
        public View getTabView(int position){
            View view =  View.inflate(ProcessActivity.this,R.layout.tab_view_item,null);

            ImageView imageView = (ImageView) view.findViewById(R.id.tab_img);
            TextView textView = (TextView) view.findViewById(R.id.tab_text);
            imageView.setImageResource(IMG_IDS[position]);
            textView.setText(ICON_TEXTS[position]);
            return view;
        }

    }
}
